package com.demo.pattern.proxy.dynamicProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author linchong
 * @version 1.0
 * @Date: 2022-05-26 23:05
 * @Description: CglibProxy$
 */
public class CglibProxy {
	public static void main(String[] args) {
		RentingHouseImpl rentingHouse = new RentingHouseImpl();
		//获取rentingHouse对象的代理对象
		//Enhancer类似于JDK动态代理中的Proxy
		//通过实现接口MethodInterceptor能够对各个方法进行拦截增强，类似于JDK动态代理中的InvocationHandler
		/*RentingHouseImpl rentingHouseProxy = (RentingHouseImpl) Enhancer.create(rentingHouse.getClass(),
				(MethodInterceptor) (obj, method, objects, methodProxy) -> {
			//obj:代理对象的引用，method:动态执行到的方法，objects:参数，methodProxy:对当前执行到的方法的一个封装
			Object result = null;
			//增强逻辑
			System.out.println("中介(代理)收取服务费3000元");
			//调用原有逻辑
			result = method.invoke(rentingHouse, objects);
			System.out.println("客户信息买了3元");
			return result;
		});*/
		//Cglib的动态代理与GDK动态代理区别，JDK要求原有委托对象必须实现接口，JDK代理，增强逻辑中需要接口,obj.getClass().getInterfaces(),
		RentingHouseImpl rentingHouseProxy = (RentingHouseImpl) ProxyFactory.getInstance().getCglibProxy(rentingHouse);
		rentingHouseProxy.rentHouse();
	}
}
